// ==UserScript==
// @name           DynaScriptControlPanel
// @namespace      jirina42@seznam.cz
// @include        http*://orion.pardus.at/menu.php
// @include        http*://chat.pardus.at/chat.php*
// @include        http*://orion.pardus.at/options.php
// @version	   2.8
// ==/UserScript==

// This is the default url for the scripts update. It should be replaced in case you want to disctribute it.
var scriptUpdateURL = "http://federation.fedfalcons.com";

// ////////////////////////////////////////////////////////////////////////
// Support for 'cookies'
// ////////////////////////////////////////////////////////////////////////
function createCookie(name, value) {
    localStorage.setItem(name, value); 
}

function readCookie (name) {
    return localStorage.getItem(name);
}

function eraseCookie(name) {
    localStorage.removeItem(name);
}

function GMcreateCookie(name,value) {
    // We use the write-through cache here. Everything written to the permanent
    // storage is written to the session storage as well so that it can be used immediately
    GM_setValue(name,value);
    createCookie (name, value);
}

function GMreadCookie(name, override) {
    // Check first if we have the value in the local storage and return it if so.
    // In case the Override is set to True, we read the GM value anyway and write
    // it into the local storage once again.
    var local = readCookie (name);
    if (local && override != true) return local;
    
    // Try to read teh GM value and return it
    try {
            var temp = GM_getValue(name);
            if(temp) {
                createCookie (name, temp);
                return temp;
            }
    } catch(err) {}
    return null;
}

function GMeraseCookie(name) {
    GM_deleteValue (name);
    eraseCookie (name);
}
// ////////////////////////////////////////////////////////////////////////
// End Support for 'cookies'
// ////////////////////////////////////////////////////////////////////////

// ////////////////////////////////////////////////////////////////////////
// Supporting Get/Set methods
// ////////////////////////////////////////////////////////////////////////
function getUniverse () {
    return document.URL.split ("//")[1].split(".")[0];
}

function getPilotID () {
    var uid = unsafeWindow.userid;
    if (uid != undefined) {
	localStorage.setItem ("po_pilot_id", uid);
	return uid;
    }
    return localStorage.getItem ("po_pilot_id");
}

function getUser () {
    try {
        return top.window.frames[1].document.getElementById('universe').getAttribute('title').substring(7);
    } catch (ex) {
	return localStorage.getItem ("po_pilot_name");
    }
    return null;
}

function getValidationCode(){
    var code = localStorage.getItem('po_sc');
    if ((code == null) || (code.length < 20)) {
        if (!localStorage.getItem ("po_invalid_code_shown")) {
            alert ("Security code invalid. Please ender valid security code in the DynaScript control panel. You'll see this warning only once but none of the scripts requiring the security code will work until you enter a valid code.");
            localStorage.setItem ("po_invalid_code_shown", "yes");
        }
        return "...";
    }
    return code;
}

function setValidationCode (code) {
    if (!code || code.length < 20) {
	alert ("The code you've provided is invalid. Please ask for a new security code.");
	localStorage.removeItem('po_sc');
	return "";
    }
    localStorage.setItem('po_sc', code);
    localStorage.removeItem ("po_invalid_code_shown");
    return code;
}

function getServerUrl(file){
    var local = localStorage.getItem ('ds_local_dev');
    if (local == "true") {
	url = localStorage.getItem('ds_local_dev_path');
	if (url == null || (file.indexOf (".php")!=-1 && url.indexOf ("file://") != -1)) var url = localStorage.getItem('ds_dynascript_address');
    } else {
	var url = localStorage.getItem('ds_dynascript_address');
    }
    if (url == null) {
        if (!localStorage.getItem ("po_invalid_url_shown")) {
            alert ("Dynascript server address is not set or it's invalid. Please ender valid server URL in the DynaScript control panel. You'll see this warning only once but none of the scripts requiring the server address will work until you enter a valid one.");
            localStorage.setItem ("po_invalid_url_shown", "yes");
        }
        return null;
    }
    if (file) {
        if (file[0] != "\/") url += "\/";
        url += file;
    }
    return url;
}

function setServerUrl (url) {
    if (!isValidURL (url)) {
	alert ("The address you've provided is invalid. Please enter plain server address without any speciffic file (e.g. http://www.myhosting.com/myinfocentre)");
	localStorage.removeItem('ds_dynascript_address');
	return "";
    }
    localStorage.setItem('ds_dynascript_address', url);
    localStorage.removeItem ("po_invalid_url_shown");
    return url;
}

function isValidURL(url) {
    
	var urlRegxp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if (urlRegxp.test(url) != true) {
		return false;
	} else {
		return true;
	}
}
// ////////////////////////////////////////////////////////////////////////
// End Supporting Get/Set methods
// ////////////////////////////////////////////////////////////////////////

// ////////////////////////////////////////////////////////////////////////
// Script loading methods
// ////////////////////////////////////////////////////////////////////////
function checkForNewScripts (force) {
    // Check the server for the new scripts
    // The Ajax response from the server has to be in the following form:
    // <div scriptName='Testing script' scriptDesc='A short description of the Testing Script' allowedUniverses='Orion;Artemis' version='1.0'>
    //   <script type='text/javascript' src='path to the .js file 1' target='page' includes='main.php;overview_stats.php'></script> // For scripts which are to be included into the page's DOM
    //   <script type='text/javascript' src='path to the .js file ...' target='GM'></script> // For scripts which have to run in the GM sandbox and have to be installed manually
    // </div>
    // <div scriptName='...'>
    //   ...
    // </div>
    //
    // The 'target' attribute controls whether the script will be loaded to the source page's DOM or to the GM sandbox.
    //
    // As parameters we're sending the current universe and user's name to the server
    // so that the server can find and return the appropriate scripts
    var uni = getUniverse ();
    var addr = getServerUrl ("/dynascript/dynascript.php");
    if (!addr) return;
     
    addr += "?universe="+uni+"&user="+getUser()+"&userid="+getPilotID()+"&vcode="+getValidationCode();
    
    if (force) {
        // Disable the Refresh button while the check is in progress
        var btn = document.getElementById ("ds_cp_refrest_scripts");
        if (btn) {
            btn.disabled = true;
            btn.setAttribute ("value", "checking...");
        }
    }
    
    var close = function (response) {
        if (force) {
            btn.setAttribute ("value", "Check for script updates");
            btn.disabled = false;
        }
    }
    GM_xmlhttpRequest({
        method: "GET",
        url: addr,
        onload: function(response) {
            var responseOK = false;
	    var responseEmpty = false;
            var div = document.createElement ("div");
            if (!response.responseText || response.responseText.length == 0) {
                responseEmpty = true;
            } else {
                div.innerHTML = response.responseText;
                try {
                    if (div.firstChild.tagName == "DIV" && div.firstChild.firstChild.tagName == "SCRIPT")
                        responseOK = true;
                } catch (ex) {}
            }
	    if (responseEmpty) {
//		GMeraseCookie ("DS_availableScriptsConfig_"+uni);
//		autoInstallScripts (div);
	    }
            if (responseOK) {
                GMcreateCookie ("DS_availableScriptsConfig_"+uni, response.responseText);
                autoInstallScripts (div);
            }
            if (force) {
                loadScriptsToControlPanel ();
            }
	    close (response);
        },
        onerror: function (response){
	    GM_log ("Error:"+response.responseText);
	    close ();
	},
        onabort: function (response){
	    GM_log ("Abort:"+response.responseText);
	    close ();
	}
    });
}

function autoInstallScripts (scripts) {
    var autoInstall = GMreadCookie ("ds_cp_autoinstall")=="true"?true:false;
    var autoUpdate = GMreadCookie ("ds_cp_autoupdate")=="true"?true:false;

    var scriptsInstalled = document.createElement ("div");
    var str = GMreadCookie ("DS_installedScriptsConfig_"+getUniverse());
    if (str) scriptsInstalled.innerHTML = str;

    var changed = false;
    
    // Now check the installed scripts if any of them has been discontinued. We would have to uninstall such script automatically
    for (var i=0; i<scriptsInstalled.childNodes.length; i++) {
        var iScript = scriptsInstalled.childNodes[i];
        var aScript = findScriptIn (iScript.getAttribute ("scriptName"), scripts);
        if (aScript) continue;
        
        iScript.parentNode.removeChild (iScript);
        changed = true;
    }
    
    // Check the downloaded scripts if there's any update for an already installed script
    if (autoInstall || autoUpdate) {
        for (var i=0; i<scripts.childNodes.length; i++) {
            var aScript = scripts.childNodes[i];
    
            if (aScript.getAttribute ("target") != "page") continue;
            iScript = findScriptIn (aScript.getAttribute ("scriptName"), scriptsInstalled);
    
            // Replace the installed script with the available one
            if (iScript && autoUpdate) {
                iScript.parentNode.insertBefore (aScript.cloneNode (true), iScript);
                iScript.parentNode.removeChild (iScript);
		setDefaultValues (aScript);
                changed = true;
            }
            if (!iScript && autoInstall){
                scriptsInstalled.appendChild (aScript.cloneNode (true));
		setDefaultValues (aScript);
                changed = true;
            }
        }
    }
    
    if (changed) {
        // Save the installed scripts back to the storage
        GMcreateCookie ("DS_installedScriptsConfig_"+getUniverse(), scriptsInstalled.innerHTML);
    }
}

function getUserConfig (script) {
    // Finds and returns user config element if exists.
    var divs = script.getElementsByTagName ("div");
    for (var i=0; i<divs.length; i++) {
	var aDiv = divs[i];
	if (aDiv.getAttribute ("name") == "user_config")
	    return aDiv;
    }
    return null;
}

function setDefaultValues (script) {
    // Sets teh default value of the script's configuration into localStorage
    var conf = getUserConfig (script);
    if (!conf) return;
    
    for (var i=0; i<conf.childNodes.length; i++) {
	var item = conf.childNodes[i];
	var value = readCookie (item.getAttribute ("name"));
	if (value == null || value.length == 0) {
	    createCookie (item.getAttribute ("name"), item.getAttribute ("default"));
	} else if (item.getAttribute ("hidden") == "true") {
	    createCookie (item.getAttribute ("name"), item.getAttribute ("default"));
	}
    }
}

function refreshScripts (force) {
    // Check for updated scripts on the server and load them in case of any updates
    
    // Set the AutoInstall and AutoUpdate to True by default on fresh installation
    var autoInstall = GMreadCookie ("ds_cp_autoinstall");
    if (autoInstall == null) GMcreateCookie ("ds_cp_autoinstall", "true");
    var autoUpdate = GMreadCookie ("ds_cp_autoupdate");
    if (autoUpdate == null) GMcreateCookie ("ds_cp_autoupdate", "true");

    // Get the date of the last version check. If it's more than one day old, check for new versions. Otherwise exit.
    var lastCheck = GMreadCookie ("DS_lastCheck");
    if (!lastCheck)
        lastCheck = 0;
    else
        lastCheck = Number (lastCheck);

    var today = new Date ();
    var todayCheck = Number (String(today.getFullYear())+String(today.getMonth())+String(today.getDate()));

    if (todayCheck<=lastCheck && force != true) return;
    // OK, the last check took place yesterday or further in the past (or never). Let's check for new versions.
    checkForNewScripts (force);
    GMcreateCookie ("DS_lastCheck", String(todayCheck));
}

function refresh () {
    var text = document.URL;
    if (text.indexOf("menu.php") < 0) {
        return;
    }

    var str = "DS_installedScriptsConfig_"+getUniverse();
    if (!readCookie(str)) {
	GMreadCookie (str, true);
    }
        if (!GMreadCookie("ds_dynascript_address")){
	GMcreateCookie("ds_dynascript_address", scriptUpdateURL);
    }
    refreshScripts (false);
}
refresh ();

// ////////////////////////////////////////////////////////////////////////
// Control panel
// ////////////////////////////////////////////////////////////////////////
function findScriptIn (name, scripts) {
    for (var i=0; i<scripts.childNodes.length; i++) {
        if (scripts.childNodes[i].getAttribute ("scriptName") == name)
            return scripts.childNodes[i];
    }
    return null;
}

function uninstallScript (evt) {
    var tbody = document.getElementById ("ds_cp_scripts");
    var scriptsInstalled = document.createElement ("div");
    var str = GMreadCookie ("DS_installedScriptsConfig_"+getUniverse());
    if (str) scriptsInstalled.innerHTML = str;
    var scriptName = evt.target.getAttribute ("scriptName");

    // Fine the scripts in the Available and Installed scripts
    var iScript = findScriptIn (scriptName, scriptsInstalled);

    // Remove the script from configuration
    var changed = false;
    if (iScript) {
        if (iScript.getAttribute ("target") == "page") {
            iScript.parentNode.removeChild (iScript);
            changed = true;
        } else {
            var response = confirm ("This is a GreaseMonkey script and you have to remove it manually in GreaseMonkey. If you have already done it, push OK to confirm it. Otherwise click Cancel, remove the script manually and then push the Uninstall button again.");
            if (response) {
                iScript.parentNode.removeChild (iScript);
                changed = true;
            }
        }
    }
    
    if (changed) {
        // Save the installed scripts back to the storage
        GMcreateCookie ("DS_installedScriptsConfig_"+getUniverse(), scriptsInstalled.innerHTML);
        // Refresh the scripts table content
        loadScriptsToControlPanel ();
    }
}

function installScript (evt) {
    var tbody = document.getElementById ("ds_cp_scripts");
    var scriptsAvailable = document.createElement ("div");
    var str = GMreadCookie ("DS_availableScriptsConfig_"+getUniverse());
    if (str) scriptsAvailable.innerHTML = str;
    var scriptsInstalled = document.createElement ("div");
    str = GMreadCookie ("DS_installedScriptsConfig_"+getUniverse());
    if (str) scriptsInstalled.innerHTML = str;
    var scriptName = evt.target.getAttribute ("scriptName");
    
    // Fine the scripts in the Available and Installed scripts
    var iScript = findScriptIn (scriptName, scriptsInstalled);
    var aScript = findScriptIn (scriptName, scriptsAvailable);

    if (aScript.getAttribute ("target") != "page") {
        var response = confirm ("This is a GreaseMonkey script and you have to install it manually in GreaseMonkey by clicking the link(s) at the right side. If you have already done it, push OK to confirm it. Otherwise click Cancel, install the script(s) manually and then push the Install button again.");
        if (!response) return;
    }

    // Replace the installed script with the available one
    if (iScript) {
        iScript.parentNode.insertBefore (aScript, iScript);
        iScript.parentNode.removeChild (iScript);
    } else {
        scriptsInstalled.appendChild (aScript);
    }
    setDefaultValues (aScript);
    
    // Save the installed scripts back to the storage
    GMcreateCookie ("DS_installedScriptsConfig_"+getUniverse(), scriptsInstalled.innerHTML);
    
    // Refresh the scripts table content
    loadScriptsToControlPanel ();
}

var show_files = false;

function loadScriptsToControlPanel () {
    var tbody = document.getElementById ("ds_cp_scripts");
    var scriptsAvailable = document.createElement ("div");
    var str = GMreadCookie ("DS_availableScriptsConfig_"+getUniverse());
    if (str) scriptsAvailable.innerHTML = str;
    var scriptsInstalled = document.createElement ("div");
    str = GMreadCookie ("DS_installedScriptsConfig_"+getUniverse());
    if (str) scriptsInstalled.innerHTML = str;

    // Set the table header. In case there's any content in the table, this will remove it.
    //tbody.innerHTML = "<tr><th>GM</th><th>Script name / Config</th><th>Version available</th><th>Version installed</th><th>Install</th><th>Script files <a id='po_ds_show_files_lnk' href='javascript:void(0);'>(show)</a></th><th>Script description</th></tr>";
    tbody.innerHTML = "<tr><th>GM</th><th>Script name / Config</th><th>Version available</th><th>Version installed</th><th>Install</th><th>Script description</th></tr>";
    
    var lnk = document.getElementById ("po_ds_show_files_lnk");
    if (lnk) {
	lnk.addEventListener ("click", function(){
		show_files = true;
		loadScriptsToControlPanel();
	    }, false);
    }
    
    var alternating = false;
    for (var i=0; i<scriptsAvailable.childNodes.length; i++) {
        var aScript = scriptsAvailable.childNodes[i];
        var row = document.createElement ("tr");
        tbody.appendChild (row);
	if (alternating) {
	    row.setAttribute ("class", "alternating");
	    alternating = false;
	} else alternating = true;
	row.setAttribute ("scriptName", aScript.getAttribute ("scriptName"));
        var iScript = findScriptIn (aScript.getAttribute ("scriptName"), scriptsInstalled);
        var iVersion = iScript==null?"---":iScript.getAttribute("version");
        var aVersion = aScript.getAttribute ("version");
        var btnLabel = "Install";
        var gm = (aScript.getAttribute("target")=="page"?"":"<font color=red style='font-weight:bold;' title='This is a Greasemonkey script so it can not be installed automatically. Please install the script(s) by clicking the script file links and install them as any other GM scripts. When you are finished with all the files please push the Installed button to confirm that you have finished.'>\>\></font>");
        var tooltip = (aScript.getAttribute("target")=="page"?"":"Install the script(s) by clicking the links on the right side and confirm succesfull installation by pushing this button then.");
        var scriptName = (getUserConfig(aScript) == null || iScript==null)?aScript.getAttribute ("scriptName"):"<a style='color:orange;' href=\"javascript:ds_show_config('"+aScript.getAttribute ("scriptName")+"', '"+getUniverse()+"');void(0);\">"+aScript.getAttribute ("scriptName")+"</a>";
	var html = "<td>"+gm+"</td>"+
                        "<td>"+scriptName+"</td>"+
                        "<td>"+aVersion+"</td>"+
                        "<td>"+iVersion+"</td>"+ // Installed version comes here
                        "<td>"+(aVersion==iVersion?"<input action='uninstall' type=button value='Uninstall'></input>":"<input action='install' type=button value='"+btnLabel+"' title='"+tooltip+"'></input>")+"</td>";  // An Install button comes here
	var scripts = aScript.getElementsByTagName ("script");
	if (show_files) {
	    html += "<td>";
	    for (var j=0; j<scripts.length; j++) {
		if (j > 0) {
		    html += "<br>";
		}
		var aFile = scripts[j];
		var filePath = aFile.getAttribute("src").split("/");
		var completeUrl = aFile.getAttribute("src");
		if (completeUrl.indexOf (":\/\/") == -1) {
		    completeUrl = getServerUrl (completeUrl);
		}
		html += "<a href='"+completeUrl+"' target='_blank'>"+filePath[filePath.length-1]+"</a>";
	    }
	    html += "</td>"
	}
	
	var longDesc = aScript.getAttribute ("longDesc");
	var desc = null;
	if (longDesc) {
	    longDesc = getServerUrl (longDesc);
	    desc = "<td><a href='"+longDesc+"' target='_blank' style='color:orange;'>"+aScript.getAttribute ("scriptDesc")+"</a></td>";
	} else {
	    desc = "<td>"+aScript.getAttribute ("scriptDesc")+"</td>";
	}
        html += "</td>"+desc;
        row.innerHTML = html;
        var aBtn = row.childNodes[4].firstChild;
        if (aBtn) {
            if (aBtn.getAttribute ("action") == "install") {
                aBtn.addEventListener ("click", installScript, true);
            } else {
                aBtn.addEventListener ("click", uninstallScript, true);
            }
	    aBtn.setAttribute ("scriptName", aScript.getAttribute ("scriptName"));
        }
    }
}

function ds_show_config (scriptName, universe) {
    // Show the configuration panel for the given script
    
    // Read the installed scripts
    var scriptsInstalled = document.createElement ("div");
    str = localStorage.getItem("DS_installedScriptsConfig_"+universe);
    if (str) scriptsInstalled.innerHTML = str;
    else return;
    
    // Find the script we want to show the config for
    var myScript = null;
    var myConf = null;
    for (var i=0; i<scriptsInstalled.childNodes.length; i++) {
	aScript = scriptsInstalled.childNodes[i];
	if (aScript.getAttribute("scriptName") == scriptName) {
	    var aConf = getUserConfig (aScript);
	    if (aConf) {
		myScript = aScript;
		myConf = aConf;
	    }
	    break;
	}
    }
    if (!myScript) return;
    
    // Find the html element where the script is shown
    var tbody = document.getElementById ("ds_cp_scripts");
    var myRow = null;
    for (var i=0; i<tbody.childNodes.length; i++) {
	var aRow = tbody.childNodes[i];
	if (aRow.getAttribute ("scriptName") == scriptName) {
	    myRow = aRow;
	    break;
	}
    }
    if (!myRow) return;
    
    // Check if the config is already shown. If so, close it.
    var config = myRow.nextSibling;
    if (config) {
	if (config.getAttribute ("scriptName") == "config") {
	    config.parentNode.removeChild(config);
	    return;
	}
    }
    
    // OK, let's create the configuration panel now and insert it to the table
    var config = document.createElement ("tr");
    config.setAttribute ("scriptName", "config");
    config.setAttribute ("class", myRow.getAttribute ("class"));
    
    // Add the panel to the table
    if (myRow.nextSibling)
	myRow.parentNode.insertBefore (config, myRow.nextSibling);
    else
	myRow.parentNode.appendChild (config);
	
    // Generate the contents
    config.innerHTML = "<td> </td>\
			<td colspan=6><table><tbody>\
			    <tr><td colspan=2><font style='color:red;'>The changes you make here are saved automatically.</font></td></tr>\
			</table></tbody></td>";
    var body = config.lastChild.firstChild.firstChild;
    
    // Loop over the config elements and add them into the panel.
    for (var i=0; i<myConf.childNodes.length; i++) {
	var aConf = myConf.childNodes[i];
	if (aConf.getAttribute ("hidden") == "true") continue;
	if (aConf.getAttribute ("type") == "bool")
	    ds_make_bool_config (aConf, body);
	else if (aConf.getAttribute ("type") == "text")
	    ds_make_text_config (aConf, body);
    }    
}
unsafeWindow.ds_show_config = ds_show_config;

function ds_make_bool_config (conf, body) {
    // Generate a single configuration item - checkbox
    var tr = document.createElement ("tr");
    body.appendChild (tr);
        
    // Make the label first
    tr.innerHTML = "<td><span title='"+conf.getAttribute("description")+"'>"+conf.getAttribute("label")+"</span></td>"
    
    // Now create the checkbox item
    var name = conf.getAttribute ("name");
    var checked = localStorage.getItem (name);
    if (checked == null) {
	checked = conf.getAttribute ("default");
    }
    var check = (checked == "true")?"checked":"";
    tr.innerHTML += "<td><input type='checkbox' "+check+" onchange=\"javascript:localStorage.setItem('"+name+"', this.checked);void(0);\"></input></td>"
}
unsafeWindow.ds_make_bool_config = ds_make_bool_config;

function ds_make_text_config (conf, body) {
    // Generate a single configuration item - text box
    var tr = document.createElement ("tr");
    body.appendChild (tr);
        
    // Make the label first
    tr.innerHTML = "<td><span title='"+conf.getAttribute("description")+"'>"+conf.getAttribute("label")+"</span></td>"
    
    // Now create the checkbox item
    var name = conf.getAttribute ("name");
    var value = localStorage.getItem (name);
    if (value == null) {
	value = conf.getAttribute ("default");
    }
    tr.innerHTML += "<td><input type='text' value='"+value+"' size='80' onchange=\"javascript:localStorage.setItem('"+name+"', this.value);void(0);\"></input></td>"
}
unsafeWindow.ds_make_text_config = ds_make_text_config;

function installControlPanel () {
    var text = document.URL;
    if (text.indexOf("options.php") < 0) {
        // Go out if we're not on the Stats page
        return;
    }
        
    // Find the place for the control panel
    var tbl = document.getElementsByTagName ("h1")[0].parentNode.parentNode.parentNode.parentNode.parentNode;
    var frm = document.createElement ("form");
    var table = tbl.cloneNode(false);
    var addr = GMreadCookie("ds_dynascript_address");
    if (!addr) addr = "";
    table.style.display = "none";
    table.setAttribute ("width", "75%");
    frm.appendChild (table);
    tbl.parentNode.appendChild (document.createElement ("br"));
    tbl.parentNode.appendChild (frm);
    table.innerHTML =   "<tbody id=ds_cp_top>\
			    <tr align=center><td><h2>DynaScript Control Panel</h2></td></tr>\
                            <tr>\
                                <td><table width='100%' style='border: 1px dotted lime;'><tbody id=ds_cp_settings>\
                                    <tr><td><input type='checkbox' id='ds_cp_autoupdate'></input>Update installed scripts automatically (non-GM scripts only)</td></tr>\
                                    <tr><td><input type='checkbox' id='ds_cp_autoinstall'></input>Install new scripts automatically (non-GM scripts only)</td></tr>\
				    <tr><td><table><tbody>\
					<tr><td>Code</td><td><input type=password id='ds_cp_security_code' size='50' value='"+(GMreadCookie("po_sc")||"")+"'></input></td></tr>\
					<tr>\
					    <td>Server</td><td><input type=text id='ds_cp_dynascript_address' size='50' value='"+addr+"'></input></td>\
					    <td><input type=button id=ds_cp_refrest_scripts value='Check for script updates'></input></td>\
					</tr>\
				    </tbody></table></td></tr>\
                                </tbody></table></td>\
                            </tr><br>\
                            <tr><td colspan=2><table style='border: 1px dotted lime;'><tbody id=ds_cp_scripts>\
                            </tbody></table></td></tr>\
                        </tbody>";

    document.getElementById ("ds_cp_autoupdate").checked = GMreadCookie ("ds_cp_autoupdate")=="true"?true:false;
    document.getElementById ("ds_cp_autoupdate").addEventListener ("change", function(){GMcreateCookie("ds_cp_autoupdate", String(this.checked))}, true);
    document.getElementById ("ds_cp_autoinstall").checked = GMreadCookie ("ds_cp_autoinstall")=="true"?true:false;
    document.getElementById ("ds_cp_autoinstall").addEventListener ("change", function(){GMcreateCookie("ds_cp_autoinstall", String(this.checked))}, true);
    document.getElementById ("ds_cp_refrest_scripts").addEventListener ("click", function(){refreshScripts(true)}, true);
    document.getElementById ("ds_cp_dynascript_address").addEventListener ("change", function(){this.value = setServerUrl (this.value)}, true);
    document.getElementById ("ds_cp_security_code").addEventListener ("change", function(){this.value = setValidationCode(this.value)}, true);
    
    // Generate the scripts table
    loadScriptsToControlPanel ();
    
    // Show the table
    table.style.display = "block";
}


installControlPanel ();
// ////////////////////////////////////////////////////////////////////////
// End Control panel
// ////////////////////////////////////////////////////////////////////////

// ////////////////////////////////////////////////////////////////////////
// Chat stuff
// ////////////////////////////////////////////////////////////////////////
function loadChatScript () {
    var text = document.URL;
    if (text.indexOf("chat.php") < 0) {
        // Go out if we're not on the Chat page

        return;
    }
    var div = document.createElement ("div");
    var head = document.getElementsByTagName('head')[0];
    
    var myScript = document.createElement ("script");
    myScript.type = "text/javascript";
    myScript.setAttribute ("src", scriptUpdateURL+"/scripts/fed_chat/fed_chat.js?time="+(new Date()).getDate ());
    //myScript.setAttribute ("src", "file:///c:/temp/pardus/OrionProject/scripts/fed_chat/fed_chat.js?time="+(new Date()).getTime ());
    head.appendChild (myScript);
}
loadChatScript();